'use client'

import { useUserStore } from '@/store/user'
import request from '@/utils/frontend/request'
import { LoadingOutlined, LockOutlined, PlusOutlined, UserOutlined } from '@ant-design/icons'
import { Button, Card, Col, Form, Input, message, Modal, Row, Upload, type UploadProps } from 'antd'
import { useState } from 'react'

interface PasswordForm {
	oldPassword: string
	newPassword: string
	confirmPassword: string
}

export default function ProfilePage() {
	const { userInfo, setUserInfo } = useUserStore()
	const [uploading, setUploading] = useState(false)
	const [passwordModalOpen, setPasswordModalOpen] = useState(false)
	const [passwordForm] = Form.useForm<PasswordForm>()
	const [messageApi, contextHolder] = message.useMessage()

	// 处理头像上传
	const handleAvatarUpload: UploadProps['customRequest'] = async ({ file }) => {
		try {
			setUploading(true)
			const formData = new FormData()
			formData.append('file', file)

			const { data: uploadData } = (await request.post('/common/upload', formData)) as ApiResponse

			// 更新用户头像
			const { data: userData } = (await request.patch(`/user/${userInfo?.id}`, {
				avatar: uploadData,
			})) as ApiResponse

			setUserInfo({ ...userInfo!, avatar: uploadData })
			messageApi.success('头像更新成功')
		} catch (error) {
			messageApi.error('头像上传失败')
		} finally {
			setUploading(false)
		}
	}

	// 处理密码修改
	const handlePasswordChange = async (values: PasswordForm) => {
		try {
			if (values.newPassword !== values.confirmPassword) {
				messageApi.error('两次输入的密码不一致')
				return
			}

			const { message: msg } = (await request.patch(`/user/${userInfo?.id}/password`, {
				oldPassword: values.oldPassword,
				newPassword: values.newPassword,
			})) as ApiResponse

			messageApi.success(msg)
			setPasswordModalOpen(false)
			passwordForm.resetFields()
		} catch (error) {
			messageApi.error('修改密码失败')
		}
	}

	return (
		<div className="p-8 max-w-6xl mx-auto">
			{contextHolder}
			<h1 className="text-2xl font-bold mb-8">个人中心</h1>

			<Row gutter={24}>
				{/* 用户信息看板 */}
				<Col span={8}>
					<Card>
						<div className="flex flex-col items-center">
							<Upload
								name="avatar"
								listType="picture-circle"
								showUploadList={false}
								customRequest={handleAvatarUpload}
								className="!w-32 !h-32"
								beforeUpload={(file) => {
									const isImage = file.type.startsWith('image/')
									if (!isImage) {
										messageApi.error('只能上传图片文件!')
									}
									const isLt5M = file.size / 1024 / 1024 < 5
									if (!isLt5M) {
										messageApi.error('图片大小不能超过 5MB!')
									}
									return isImage && isLt5M
								}}
							>
								{userInfo?.avatar ? (
									<img
										src={userInfo.avatar}
										alt="avatar"
										className="w-full h-full rounded-full object-cover"
									/>
								) : (
									<div>
										{uploading ? <LoadingOutlined /> : <PlusOutlined />}
										<div className="mt-2">更换头像</div>
									</div>
								)}
							</Upload>
							<h2 className="text-xl font-medium mt-4">{userInfo?.nickname}</h2>
							<p className="text-gray-500">{userInfo?.username}</p>
						</div>
						<div className="mt-6">
							<p>
								<UserOutlined className="mr-2" />
								角色：{userInfo?.role === 'admin' ? '管理员' : '普通用户'}
							</p>
							<p>
								<LockOutlined className="mr-2" />
								状态：{userInfo?.status === 'online' ? '在线' : '离线'}
							</p>
						</div>
					</Card>
				</Col>

				{/* 个人信息编辑 */}
				<Col span={16}>
					<Card title="账号安全">
						<div className="flex items-center justify-between p-4 border-b">
							<div>
								<h3 className="font-medium">登录密码</h3>
								<p className="text-gray-500 text-sm">建议定期更换密码，确保账号安全</p>
							</div>
							<Button type="primary" onClick={() => setPasswordModalOpen(true)}>
								修改密码
							</Button>
						</div>
					</Card>
				</Col>
			</Row>

			{/* 修改密码弹窗 */}
			<Modal
				title="修改密码"
				open={passwordModalOpen}
				onOk={() => passwordForm.submit()}
				onCancel={() => {
					setPasswordModalOpen(false)
					passwordForm.resetFields()
				}}
			>
				<Form form={passwordForm} layout="vertical" onFinish={handlePasswordChange}>
					<Form.Item
						name="oldPassword"
						label="当前密码"
						rules={[{ required: true, message: '请输入当前密码' }]}
					>
						<Input.Password />
					</Form.Item>
					<Form.Item
						name="newPassword"
						label="新密码"
						rules={[{ required: true, message: '请输入新密码' }]}
					>
						<Input.Password />
					</Form.Item>
					<Form.Item
						name="confirmPassword"
						label="确认新密码"
						rules={[{ required: true, message: '请再次输入新密码' }]}
					>
						<Input.Password />
					</Form.Item>
				</Form>
			</Modal>
		</div>
	)
}
